package config

import (
	"os"
	"strconv"

	"github.com/joho/godotenv"
)

// Config 应用程序配置结构体
type Config struct {
	DBHost     string
	DBPort     string
	DBUser     string
	DBPassword string
	DBName     string
	DBCharset  string
	DBParseTime string
	DBLoc      string
	ServerPort string
	JWTSecret  string
	JWTExpire  string
	AppName    string
	AppDebug   string
}

// LoadConfig 加载配置
func LoadConfig() (*Config, error) {
	// 加载环境变量文件
	if err := godotenv.Load(); err != nil {
		return nil, err
	}

	// 从环境变量获取配置
	serverPort := os.Getenv("SERVER_PORT")
	if serverPort == "" {
		serverPort = "8080" // 默认端口
	}

	return &Config{
		DBHost:     os.Getenv("DB_HOST"),
		DBPort:     os.Getenv("DB_PORT"),
		DBUser:     os.Getenv("DB_USER"),
		DBPassword: os.Getenv("DB_PASSWORD"),
		DBName:     os.Getenv("DB_NAME"),
		DBCharset:  os.Getenv("DB_CHARSET"),
		DBParseTime: os.Getenv("DB_PARSE_TIME"),
		DBLoc:      os.Getenv("DB_LOC"),
		ServerPort: serverPort,
		JWTSecret:  os.Getenv("JWT_SECRET"),
		JWTExpire:  os.Getenv("JWT_EXPIRE"),
		AppName:    os.Getenv("APP_NAME"),
		AppDebug:   os.Getenv("APP_DEBUG"),
	}, nil
}

// GetDSN 获取数据库连接字符串
func (c *Config) GetDSN() string {
	return c.DBUser + ":" + c.DBPassword + "@tcp(" + c.DBHost + ":" + c.DBPort + ")/" + c.DBName + "?charset=" + c.DBCharset + "&parseTime=" + c.DBParseTime + "&loc=" + c.DBLoc
}

// GetPaginationParams 获取分页参数
func GetPaginationParams(page, pageSize string) (int, int) {
	p, _ := strconv.Atoi(page)
	if p <= 0 {
		p = 1
	}

	ps, _ := strconv.Atoi(pageSize)
	if ps <= 0 {
		ps = 10
	}

	return p, ps
}